package service.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/code")
public class CheckcodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1:创建一个图片对象，在内存中生成图片，把它加载到内存
        BufferedImage image = new BufferedImage(100,50, BufferedImage.TYPE_INT_RGB);


        //2.美化图片
//填充背景颜色
        Graphics g = image.getGraphics();
g.setColor(Color.pink);//设置画笔颜色
//填充矩形结构颜色,具体什么颜色由setColor（）决定
        g.fillRect(0,0,100,50);
//画边框,边框颜色由setColor（）决定
       g.setColor(Color.green);
        g.drawRect(0,0,99,49);
//0,0表示 左上角顶点的坐标
//画验证码
        g.setColor(Color.BLACK);
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
        Random r= new Random();
        for (int i = 0; i < 4; i++) {
            int index = r.nextInt(str.length());
            char ch = str.charAt(index);

            g.drawString(ch+"",100/5*i,50/2);
        }
//画干扰线
        //随机生成坐标点
        for (int i = 0; i < 10; i++) {
            int x1 =r.nextInt(100);
            int x2 = r.nextInt(100);
            int   y1 = r.nextInt(50);
            int y2 = r.nextInt(50);
            g.drawLine(x1,y1,x2,y2);
        }


/*
一个点由两个坐标固定，所以需要四个参数，分别表示
* */


                //3.将图片输出到页面展示 将内存中的图片以 jpg 格式 输出到页面中
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }
}
